package com.itheima.tlias.tliasweb.service.impl;

import com.itheima.tlias.tliasweb.entity.Dept;
import com.itheima.tlias.tliasweb.entity.DeptLog;
import com.itheima.tlias.tliasweb.mapper.DeptMapper;
import com.itheima.tlias.tliasweb.pojo.AddDeptDTO;
import com.itheima.tlias.tliasweb.service.DeptLogService;
import com.itheima.tlias.tliasweb.service.DeptService;
import com.itheima.tlias.tliasweb.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

//部门业务实现类
@Slf4j
@Service
// @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpService empService;

    @Autowired
    private DeptLogService logService;


    @Override
    public List<Dept> list() {
        // 调用mapper 查询mysql
        return deptMapper.selectAll();
    }

    @Override
    public boolean deleteById(Integer id) {
        int result = deptMapper.deleteById(id);
        return result>0;
    }

    @Override
    public boolean add(AddDeptDTO dto) {
        Dept dept = new Dept();
        dept.setName(dto.getName());
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        // result代表的是影响的记录的行数
        deptMapper.insert(dept);
        return true;
    }

    @Override
    public Dept getById(Integer id) {
        return deptMapper.selectById(id);
    }

    @Override
    public boolean update(Dept dept) {
        int result = deptMapper.update(dept);
        return result>0;
    }

    @Override
    // Transactional做事务控制，rollbackFor设置回滚的异常类型
    @Transactional(rollbackFor = Exception.class)
    public void dismissDept(Integer id) throws Exception{
        boolean success = true;
        try{
            // 根据id删除部门
            deptMapper.deleteById(id);
            // 模拟出了异常
            if(true){
                success = false;
                throw new Exception("普通异常");
            }
            // 根据部门id 删除部门下的所有的员工
            empService.deleteByDeptId(id);
        }finally {
            // 肯定会执行，记录操作日志，方便审计
            DeptLog deptlog = new DeptLog();
            deptlog.setCreateTime(LocalDateTime.now());
            deptlog.setDescription(success?"success":"fail");
            logService.insert(deptlog);
        }

    }
}